﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Bzzb.Controllers
{
    public class UploadController : BaseController
    {
        private readonly ILogger<UploadController> _logger;

        private readonly IWebHostEnvironment _env;

        private readonly IConfiguration _configuration;
        public UploadController(ILogger<UploadController> logger, IWebHostEnvironment env, IConfiguration configuration, IFreeSql fsql) : base(fsql)
        {
            this._env = env;
            this._logger = logger;
            this._configuration = configuration;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Res(List<IFormFile> files, [FromForm] string dir)
        {
            string uploadPath = Path.Combine(_env.WebRootPath, "upload", dir);
            List<string> urls = new();
            _logger.LogWarning(_env.WebRootPath);
            _logger.LogWarning($"获取appsettings.json中UploadUrl的值：{_configuration.GetValue<string>("UploadUrl")}");
            long size = files.Sum(f => f.Length);
            foreach (var formFile in files)
            {
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + formFile.FileName;
                if (formFile.Length > 0)
                {
                    if (!Directory.Exists(uploadPath)) {
                        Directory.CreateDirectory(uploadPath);
                    }
                    var filePath = Path.Combine(uploadPath, fileName);

                    _logger.LogWarning(filePath);

                    using (var stream = System.IO.File.Create(filePath))
                    {
                        await formFile.CopyToAsync(stream);
                    }

                    urls.Add(_configuration.GetValue<string>("UploadUrl") + $"/upload/{dir}/" + fileName);
                }
            }
            return RenderJson(data: urls);
        }
    }
}
